﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp5
{
    class 泛型
    {
        public 泛型()
        {
            MyClassT<int> myClassT = new MyClassT<int>();
            Console.WriteLine("求和：" + myClassT.Add(1, 2));

            List<int> list = new List<int>() { 1, 2, 3, 4 };
            Console.WriteLine("累加：" + Calculate.Sum<int>(list));
        }
    }

    //泛型接口，泛型TData可以不用前缀T，但是一般加上更好
    interface ICalculate<TData>
    {
        TData Data { get; set; }
        TData Add(TData data1, TData data2);
    }

    //泛型委托
    delegate TOutput Converter<TInput, TOutput>();

    class MyClassT<TData> : ICalculate<TData>
    {
        public TData Data { get; set; }

        public TData Add(TData data1, TData data2)
        {
            return (TData)((dynamic)data1 + (dynamic)data2);
        }
    }

    class Calculate
    {
        public static T Sum<T>(List<T> items)
        {
            dynamic sumData = 0;
            for (int i = 0; i < items.Count; i++)
            {
                sumData += items[i];
            }
            return sumData;
        }
    }
}
